package com.nf.health.app.activity.home;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.nf.health.app.Constants;
import com.nf.health.app.R;
import com.nf.health.app.activity.global.BaseActivity;
import com.nf.health.app.http.Act;
import com.nf.health.app.http.Apis;
import com.nf.health.app.models.WebModel;
import com.nf.health.app.utils.NetUtil;
import com.nf.health.app.utils.SharedUtils;
import com.nf.health.app.utils.ViewUtil;
import com.nf.health.app.utils.WebViewUtils;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 院内导航
 * Created by Administrator on 2017/4/18.
 */
public class NewWebViewActivity extends BaseActivity {


    /**
     * 公共webView
     * private  String  id ="";//id标识
     * private String url = "";//要跳转的ＵＲＬ
     * private String title;//要跳转的title
     * private boolean isShowRightImg;//是否显示右侧的按钮，默认为false，不显示
     * private Object object;//附加字段 -,可以为任何基本类型
     */
    private final UMSocialService mController = UMServiceFactory.getUMSocialService(Constants.DESCRIPTOR);

    private String imageHeadUrl = "";//要分享的头像
    private String sharedContentMsg = "";//要分享的内容
    private String sharedTitle = "";//要分享的title

    @Bind(R.id.iv_back_title)
    ImageView iv_back_title;//左侧返回键
    @Bind(R.id.tv_title_title)
    TextView tv_title_title;//中间标题 title
    @Bind(R.id.iv_title_right1)
    ImageView iv_title_right1;// 最右侧imageView 1
    @Bind(R.id.iv_title_right2)
    ImageView iv_title_right2;// 最右侧imageView 2
    @Bind(R.id.tv_title_right)
    TextView tv_title_right;// 最右侧要显示的文本 2

    @Bind(R.id.wb_comment_webview)
    WebView wb_comment_webview;
    String url = "";

    private WebModel webModel;
    private String favoriteID = "";//文章的id
    private String vtype = "";//用于传值

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContent(R.layout.activity_webview);
        ButterKnife.bind(this);
        // ViewUtil.setText(this, R.id.tv_title_title, "健康明白人知识大赛");
        regisitListener();
        initView();
    }

    private void regisitListener() {
        iv_back_title.setOnClickListener(this);
        iv_title_right1.setOnClickListener(this);
        iv_title_right2.setOnClickListener(this);
        tv_title_right.setOnClickListener(this);
    }
    @Override
    protected void onResume() {
        super.onResume();
        wb_comment_webview.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        wb_comment_webview.onPause();
    }
    private void initView() {
        wb_comment_webview = WebViewUtils.getMyInitWebView(wb_comment_webview, this);
        wb_comment_webview.setWebViewClient(wvc);
        webModel = (WebModel) getIntent().getSerializableExtra(WebModel.WEBFLAG_TAG);
        url = webModel.getUrl();

        String from = getIntent().getStringExtra(Constants.FROM);

        if(webModel.isShowRightImg1()) {//显示右侧第一张图片
            try {
                imageHeadUrl = webModel.getObject2().toString();//获取要分享的头像
                sharedContentMsg = webModel.getObject3().toString();//获取要分享的内容
                sharedTitle = webModel.getObject4().toString();//获取要分享的title
            } catch (Exception e) {
                e.printStackTrace();
            }
            iv_title_right1.setVisibility(View.VISIBLE);
            if (webModel.getTAG_USER_SIGN_RIGHT1() == 1) {
                iv_title_right1.setImageResource(R.drawable.ic_collection);//收藏
            }
        }else{
            iv_title_right1.setVisibility(View.GONE);
        }


        if ("navigation".equals(from)) {
            String hid = webModel.getObject().toString();
            provider.getYLHReferral(hid);
        }
        if (webModel.isShowRightImg1()) {//显示右侧第一张图片
            iv_title_right1.setVisibility(View.VISIBLE);
            if (webModel.getTAG_USER_SIGN_RIGHT1() == 1) { //
                iv_title_right1.setImageResource(R.drawable.iv_go_share);//分享
            }
        } else {
            iv_title_right1.setVisibility(View.GONE);
        }

        if (webModel.isShowRightImg2()) {//显示右侧第二张图片
            iv_title_right2.setVisibility(View.VISIBLE);
            if (webModel.getTAG_USER_SIGN_RIGHT2() == 1) { //
                iv_title_right2.setImageResource(R.drawable.ic_collection);//收藏
            }

        } else {
            iv_title_right2.setVisibility(View.GONE);
        }

        if (webModel.isShowRightText()) {//显示右侧标题
            tv_title_right.setVisibility(View.VISIBLE);
        } else {
            tv_title_right.setVisibility(View.GONE);
        }

        //初始化接口调用：
        if (webModel.getTAG_USER_SIGN_RIGHT2() == 1) {//是否是可以收藏的
            favoriteID = webModel.getId();
            vtype = (String) webModel.getObject();
            provider.getMyFavoriteStatus(favoriteID, vtype);
        }

        //显示title
        if (!TextUtils.isEmpty(webModel.getTitle())) {
            ViewUtil.setText(this, R.id.tv_title_title, webModel.getTitle());
        }


        //加载url
        try {
            if (NetUtil.isNetworkAvailable(this)) {
                showLoading();
                boolean isLoadHtmlLoadcalUrl = webModel.isLoadHtmlLoadcalUrl();
                if (isLoadHtmlLoadcalUrl) {//加载本地的Url
                    //wb_comment_webview.loadData(URLEncoder.encode(url, "utf-8"), "text/html",  "utf-8");
                    wb_comment_webview.loadDataWithBaseURL(null, url, "text/html", "utf-8", null);
                } else {//加载网络的url
                    if(!TextUtils.isEmpty(url)){
                        wb_comment_webview.loadUrl(url+ Apis.WEBVIEW_PLETEFORM);
                    }
                }
            } else {//无网的话进行提示
                showToast(getResources().getString(R.string.l_loading_connect_err));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        //显示网页中后台的返回的title监听
        wb_comment_webview.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                ViewUtil.setText(NewWebViewActivity.this, R.id.tv_title_title, title);
            }
        });
    }

    @Override
    public void handleActionSuccess(String actionName, Object object) {
        super.handleActionSuccess(actionName, object);
        switch (actionName) {
            case Act.Flag.FLAG_GET_MY_FAVORITE_STATUS://收藏状态
                String flag = (String) object;
                if (flag.equals("1")) {//已经收藏收藏
                    iv_title_right2.setImageResource(R.drawable.ic_collection_checked);//收藏
                    iv_title_right2.setTag(R.drawable.ic_collection_checked);
                } else if (flag.equals("0")) {//没有收藏收藏
                    iv_title_right2.setImageResource(R.drawable.ic_collection);//收藏
                    iv_title_right2.setTag(R.drawable.ic_collection);
                }
                break;
            case Act.Flag.FLAG_GOTOFAVOTITE_ORLIST://请求收藏或者是取消
                Integer tag = (Integer) iv_title_right2.getTag();
                if (tag == R.drawable.ic_collection_checked) {//取消收藏
                    iv_title_right2.setImageResource(R.drawable.ic_collection);
                    iv_title_right2.setTag(R.drawable.ic_collection);
                } else if (tag == R.drawable.ic_collection) {
                    iv_title_right2.setImageResource(R.drawable.ic_collection_checked);
                    iv_title_right2.setTag(R.drawable.ic_collection_checked);
                }
                break;
            case Act.Flag.FLAG_GET_YLH_REFERRAL://请求收藏或者是取消
                JSONObject object1 =JSONObject.parseObject(object + "");
                String url = object1.getString("tourl"); //http://test.mbank.nf1000.com/public/share/h502.action?vtype=1&id=20
                wb_comment_webview.setInitialScale(25);//为25%，最小缩放等级
                WebSettings setting = wb_comment_webview.getSettings();
                setting.setDisplayZoomControls(false);
                setting.setJavaScriptEnabled(true);
                setting.setBuiltInZoomControls(true);
                wb_comment_webview.loadUrl(url+Apis.WEBVIEW_PLETEFORM);
                break;
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.iv_back_title://点击返回键
                finish();
                break;
            case R.id.iv_title_right1:
                if (webModel.getTAG_USER_SIGN_RIGHT1() == 1) { //分享
                    SharedUtils.initCustomShareBoard(this);
                    SharedUtils.configPlatforms(mController, this);
                    SharedUtils.setShareContent(mController, this, imageHeadUrl, url, sharedContentMsg, sharedTitle);
                }
                break;
            case R.id.iv_title_right2:
                Integer flag = (Integer) iv_title_right2.getTag();
                if (webModel.getTAG_USER_SIGN_RIGHT2() == 1) { //收藏或者是取消搜藏
                    if (flag == R.drawable.ic_collection_checked) {//取消收藏
                    } else if (flag == R.drawable.ic_collection) {//去收藏
                    }
                    provider.gotoFavotiteOrList(favoriteID, vtype);
                }
                break;
            case R.id.tv_title_right:
                break;
        }
    }

    // 创建WebViewClient对象
    WebViewClient wvc = new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            // 使用自己的WebView组件来响应Url加载事件，而不是使用默认浏览器器加载页面
            wb_comment_webview.loadUrl(url);
            // 记得消耗掉这个事件。给不知道的朋友再解释一下，Android中返回True的意思就是到此为止吧,事件就会不会冒泡传递了，我们称之为消耗掉
            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            //Toast.makeText(getApplicationContext(), "WebViewClient.onPageFinished", Toast.LENGTH_SHORT).show();
            super.onPageFinished(view, url);
            hideLoading();
        }


        @Override
        public void onLoadResource(WebView view, String url) {
            //Toast.makeText(getApplicationContext(), "WebViewClient.onLoadResource", Toast.LENGTH_SHORT).show();
            super.onLoadResource(view, url);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            //Toast.makeText(getApplicationContext(), "WebViewClient.onReceivedError", Toast.LENGTH_SHORT).show();
            super.onReceivedError(view, errorCode, description, failingUrl);
            hideLoading();
        }

        @Override
        public void onScaleChanged(WebView view, float oldScale, float newScale) {
            //Toast.makeText(getApplicationContext(), "WebViewClient.onScaleChanged", Toast.LENGTH_SHORT).show();
            super.onScaleChanged(view, oldScale, newScale);
        }

    };


    /**
     * 设置回退 覆盖Activity类的onKeyDown(int keyCoder,KeyEvent event)方法
     * goBack()表示返回webView的上一页面
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return WebViewUtils.onBack(keyCode, event, wb_comment_webview, this);
    }

}
